package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {


    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @param userId:          用户ID
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {
        //1.根据订单编号+支付方式查询本地交易记录，如果存在 且状态为：未支付返回即可
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        queryWrapper.eq(PaymentInfo::getPayWay, paymentType);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.构建本地交易记录对象
        paymentInfo = new PaymentInfo();
        //2.1 判断购买类型-处理订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //2.1.1 远程调用订单服务获取订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单不存在！");
            //2.1.2 判断订单状态 要求是：未支付 0901-未支付 0902-已支付 0903-已取消
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
                throw new GuiguException(400, "订单状态有误！");
            }
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //2.2 判断购买类型-处理充值
            //2.2.1 远程调用账户服务获取充值信息
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值记录不存在");
            //2.2.2 判断充值状态 要求是：支付中 0901-未支付 0902-已支付 0903-已取消
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())) {
                throw new GuiguException(400, "充值状态有误！");
            }
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值：" + rechargeInfo.getRechargeAmount() + "元");
        }
        //2.3 给其他本地交易记录对象其他属性赋值
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //2.4 支付宝/微信端交易编号，回调时间，回调内容 等待支付成功后，微信回调才更新
        //paymentInfo.setOutTradeNo();
        //paymentInfo.setCallbackContent();
        //paymentInfo.setCallbackTime();
        //3.保存本地交易记录
        this.save(paymentInfo);
        return paymentInfo;
    }

    /**
     * 支付成功后，处理本地交易记录以及订单业务处理、充值业务处理
     *
     * @param transaction 微信交易对象
     * @param payWay      支付方式
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentStatus(Transaction transaction, String payWay) {
        //1.根据订单编号+付款方式查询本地交易记录
        String orderNo = transaction.getOutTradeNo();
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        queryWrapper.eq(PaymentInfo::getPayWay, payWay);
        PaymentInfo paymentInfo = this.getOne(queryWrapper);
        if (paymentInfo != null && SystemConstant.PAYMENT_STATUS_UNPAID.equals(paymentInfo.getPaymentStatus())) {
            //2.更新本地交易记录。状态：已支付
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            //微信/支付宝端交易订单号
            paymentInfo.setOutTradeNo(transaction.getTransactionId());
            paymentInfo.setCallbackContent(transaction.toString());
            paymentInfo.setCallbackTime(new Date());
            this.updateById(paymentInfo);

            //3.处理不同支付类型：1301-订单 1302-充值
            String paymentType = paymentInfo.getPaymentType();
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                //3.1 处理支付类型为订单：远程调用订单服务完成
                Result result = orderFeignClient.orderPaySuccess(orderNo);
                if (!ResultCodeEnum.SUCCESS.getCode().equals(result.getCode())) {
                    log.error("[支付服务]远程调用订单处理订单支付成功异常", result.getMessage());
                    throw new GuiguException(400, "变更订单状态异常！");
                }
            } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
                //3.2 处理支付类型为充值：远程调用账户服务完成
                Result result = accountFeignClient.rechargePaySuccess(orderNo);
                if (!ResultCodeEnum.SUCCESS.getCode().equals(result.getCode())) {
                    log.error("[支付服务]远程调用账户处理充值成功业务异常", result.getMessage());
                    throw new GuiguException(400, "充值异常！");
                }
            }

        }

    }
}
